package com.atguigu.gulimall.seckill.scheduled;

import com.atguigu.gulimall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SeckillSkuScheduled {

    private final String upload_lock = "seckill:upload:lock";

    @Autowired
    SeckillService seckillService;

    @Autowired
    RedissonClient redissonClient;
    /**
     * 定时任务幂等性 添加分布式锁
     */
    @Scheduled(cron = "0/30 * * * * ?")
    public void uploadSeckillSkuLates30Days() {

        //1、重复上架无需处理
        log.warn("上架商品秒杀信息.........");
        RLock lock = redissonClient.getLock(upload_lock);
        lock.lock(10, TimeUnit.SECONDS);
        try {
            seckillService.uploadSeckillSkuLates30Days();
            log.info("上架商品秒杀信息结束.........");

        }finally {
            // 加上判断，防止解锁线程和当前线程不是同一个线程
            if (lock.isHeldByCurrentThread())
            {
                lock.unlock();

            }
        }



    }
}
